import event from "../event";
import util from "../util";
import requestConfig from "../request/request.config";
import request from "../request";

let socket = null;
let isHasConnectWebSocket = false;
let socketUUID = null;

let connect = async (kantbootMemory) => {
    if (socket?.readyState === 1 || isHasConnectWebSocket) {
        return;
    }
    // 是否有未断开的websocket
    isHasConnectWebSocket = false;

    await checkConnect().then((res) => {
      isHasConnectWebSocket = true;
      console.log("已经有websocket连接");
    }).catch((res) => {
        isHasConnectWebSocket = false;
        console.log("没有websocket连接");
    });

    if (isHasConnectWebSocket) {
        return;
    }

    socketUUID = util.generateUUID(69);
    const wsProtocol = requestConfig.websocketAddress;
    socket = new WebSocket(`${wsProtocol}/${kantbootMemory}`);

    socket.onopen = () => {
        console.log('WebSocket连接成功');
        // 发送连接上
        event.emit("websocket:connect", socketUUID);
    };

    event.on("websocket:connect", (uuid) => {
        if (uuid !== socketUUID) {
            socket.close();
        }
    });

    event.on("websocket:isConnect", () => {
        // 检测this.socket是还在连接中
        if (socket.readyState === 1) {
            // console.log("检测到了")
            event.emit("websocket:hasConnect");
        } else {
            // 关闭websocket
            socket.close();
        }
    });

    socket.onmessage = (event) => {
        console.log('WebSocket收到消息:', event.data);
    };

    socket.onerror = (error) => {
        if (socket.readyState === 1) {
            return;
        }
        event.emit("websocket:close", socketUUID);
        console.error('WebSocket错误:', error);
    };

    socket.onclose = () => {
        event.emit("websocket:close", socketUUID);
        console.log('WebSocket连接关闭');
    };
}

/**
 * 检测是否有websocket连接，如果没有则重新连接
 */
let checkConnect = () => {
    // 发送事件，确认是都有websocket没有断开
    event.emit("websocket:isConnect");

    return new Promise((resolve,reject) => {
        event.on("websocket:hasConnect", () => {
            isHasConnectWebSocket = true;
            resolve(true);
        });
        setTimeout(() => {
            if(isHasConnectWebSocket){
                return;
            }
            isHasConnectWebSocket = false;
            reject(false);
        }, 3000);
    });

}

let requestAndConnect = async () => {
    await new Promise((resolve, reject) => {
        request.send({
            uri: "/middleground-common-web/tokenMemory/generateMemory",
            stateSuccess: (res) => {
                connect(res.data);
                resolve();
            },
            stateFail: (res) => {
                console.error(res);
                reject();
            }
        });
    })
}

let start = () => {

    setInterval(() => {
        checkConnect().then((res) => {
            // console.log("已经有websocket连接,----");
        }).catch((rej)=>{
            // console.log("没有websocket连接,重新连接,---");
            requestAndConnect();
        })
    },5000);

    event.on("websocket:close", async (uuid) => {
        isHasConnectWebSocket = false;
        requestAndConnect()
    });
    requestAndConnect()
}

export default {
    connect,
    requestAndConnect,
    start
}
